package spcpy

import (
	"fmt"
	"gitee.com/ymofen/gobase"
	"gitee.com/ymofen/golog"
	"github.com/spf13/cobra"
	"time"
)

func init() {
	gobase.ArgFuncRegister("file2caster", gobase.ArgFuncOption{Catalog: "corbaRoot", Func: func(args string, tag interface{}) (val interface{}, err error) {
		var cbrunner CorbaRunner
		localFile := "ssr2file.rtcm"
		casterAddr := fmt.Sprintf(":2101")
		intervalScript := ""
		var addCorbaTask = &cobra.Command{
			Use: "file2caster",
			Run: func(cmd *cobra.Command, args []string) {
				fmt.Printf("localFile:%s\n", localFile)
				fmt.Printf("casterAddr:%s\n", casterAddr)
				cbrunner.SubConf = fmt.Sprintf("conntype=datafrom&interval=30s&datafrom=file://%s&checkChanged=crc", gobase.UrlEncode0(localFile))
				cbrunner.PubConf = fmt.Sprintf("conntype=caster.pub.ntripclient&connstr=%s&mountpoint=SSR&mpflag=1&maxonline=0&auth=", gobase.UrlEncode0(casterAddr))
				cbrunner.Id = "file2caster"
				cbrunner.Run()
				gobase.HookExitSignalAndInterval(0, time.Second*30, func() {
					if len(intervalScript) > 0 {

					}
				})
			},
		}
		addCorbaTask.Flags().StringVarP(&localFile, "localFile", "i", "", "")
		addCorbaTask.Flags().StringVarP(&casterAddr, "casterAddr", "d", "", "")
		addCorbaTask.Flags().StringVarP(&intervalScript, "intervalScript", "s", "", "")
		return addCorbaTask, nil
	}})

	gobase.ArgFuncRegister("addSPCpyCmd", gobase.ArgFuncOption{Catalog: "corbaRoot", Func: func(args string, tag interface{}) (val interface{}, err error) {
		var cbrunner CorbaRunner
		var addCorbaTask = &cobra.Command{
			Use: "spcpy",
			Run: func(cmd *cobra.Command, args []string) {
				golog.Infof("subConf:%s", cbrunner.SubConf)
				golog.Infof("pubConf:%s", cbrunner.PubConf)
				cbrunner.Run()
				gobase.HookExitSignalAndInterval(0, time.Second*10, func() {

				})
			},
		}
		addCorbaTask.Flags().StringVarP(&cbrunner.SubConf, "subConf", "i", "conntype=datafrom&connstr=", "")
		addCorbaTask.Flags().StringVarP(&cbrunner.PubConf, "pubConf", "o", "conntype=caster&connstr=", "")
		return addCorbaTask, nil
	}})

}

type CorbaRunner struct {
	Id      string
	SubConf string
	PubConf string
	spcpy   SPCpy
}

func (this *CorbaRunner) Run() error {
	if len(this.Id) == 0 {
		this.Id = "SPCpy"
	}
	this.spcpy.Init()
	this.spcpy.UpdateConf(this.SubConf, this.PubConf)
	return nil
}
